<template>
  <div class="attractionsBox">
    <div class="top">
      <el-button
        @click="addScenicSpot"
        style="margin-right: 20px"
        type="primary"
        :icon="Plus"
        v-if="userStore.getUser() !== null && userStore.getUser().roles === 'ROLE_ADMIN'"
      >
        新建
      </el-button>
      <!-- <el-select
        v-model="statusValue"
        placeholder="选择状态"
        size="large"
        style="width: 200px"
      >
        <el-option label="正常" :value="1"> </el-option>
        <el-option label="已禁用" :value="0"> </el-option>
      </el-select> -->
    </div>
    <div class="bottom">
      <el-table :data="tableData" size="large" style="width: 100%">
        <el-table-column label="序号" prop="id" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="图片">
          <template #default="scope">
            <div style="z-index:999999" class="demo-image__preview">
              <el-image
                style="width: 120px; height: 80px"
                preview-teleported="true"
                :src="scope.row.pictureUrl"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="srcList"
                fit="cover"
              />
            </div>
            <!-- <img :src="scope.row.pictureUrl" alt="图片未加载" /> -->
          </template>
        </el-table-column>
        <el-table-column label="描述" prop="description" />

        <el-table-column label="操作" width="230">
          <template #default="scope">
            <el-button
              size="large"
              type="primary"
              :icon="Edit"
              @click="handleEdit(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="large"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @current-change="getScenicSpot"
          @prev-click="getScenicSpot(pageData.current - 1)"
          @next-click="getScenicSpot(pageData.current + 1)"
          layout="prev, pager, next"
          :total="pageData.total"
        />
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form :ref="userFormRef" :rules="rules" :model="form">
      <el-form-item label="景区序号" prop="id">
        <el-input v-model="form.id" autocomplete="off" />
      </el-form-item>
      <el-form-item label="景区名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="景区图片" prop="pictureUrl">
        <el-upload
          ref="image"
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="uploadImage"
        >
          <img v-if="form.pictureUrl" :src="form.pictureUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="景区描述" prop="description">
        <el-input rows="5" v-model="form.description" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancle">取消</el-button>
        <el-button type="primary" @click="deal"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- <div class="demo-image__preview">
    <el-image
      style="width: 100px; height: 100px"
      :src="url"
      :zoom-rate="1.2"
      :max-scale="7"
      :min-scale="0.2"
      :preview-src-list="srcList"
      :initial-index="4"
      fit="cover"
    />
  </div> -->
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, UploadProps, FormInstance } from "element-plus";
import {
  createScenicSpotAPI,
  deleteScenicSpotAPI,
  searchAllScenicSpotAPI,
  updateScenicSpotAPI,
  uploadImageAPI,
} from "../../apis/scenicSpot";
import { useUserStore } from "../../stores/userStore";
import { useRouter } from "vue-router";
import axios from "axios";

// const url = "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg";
const srcList = ref([
  "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
  "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
]);

const userStore = useUserStore();
const router = useRouter();
//FormInstance类型从element-plus引入
const userFormRef = ref<FormInstance>();

const dialogTitle = ref("新建景点");

const dialogFormVisible = ref(false);

const pageData = ref({
  current: 1,
  total: 0,
});

const image = ref();

const uploadImage = async (uploadFile) => {
  console.log(uploadFile);

  let data = new FormData();

  data.append("file", uploadFile.raw);

  const res = await uploadImageAPI(data);

  // 自测试
  // const res = await axios({
  //   url:"http://localhost:8081/api/upload/demo",
  //   method:"POST",
  //   data,
  // })

  if (res.data.code === 1) {
    form.value.pictureUrl = res.data.data;
  }
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  //只支持重置表单上prop定义的字段，
  //如果表单:model绑定的是对象中的属性值 :model="obj.form"
  //prop要设置为  prop="form.xxx"
};

const addScenicSpot = () => {
  dialogTitle.value = "新建景点";

  form.value = {
    id: "",
    name: "",
    pictureUrl: "",
    description: "",
  };

  dialogFormVisible.value = true;
};

const form = ref({
  id: "",
  name: "",
  pictureUrl: "",
  description: "",
});

const statusValue = ref();

interface ScenicSpot {
  id: string;
  name: string;
  pictureUrl: string;
  description: string;
}

const search = ref("");

const handleEdit = (index: number, row: ScenicSpot) => {
  dialogTitle.value = "编辑景点";

  form.value = JSON.parse(JSON.stringify(row));

  dialogFormVisible.value = true;
};
const handleDelete = async (index: number, row: ScenicSpot) => {
  let flag = confirm("你确定要删除吗");

  if (flag == true) {
    const res = await deleteScenicSpotAPI(row.id);

    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      getAllScenicSpot();
    } else ElMessage.error("删除失败");
  }
};


const getScenicSpot = (page: number) => {
  if (page < 1) return;

  if (page > pageData.value.total) return;

  pageData.value.current = page;

  getAllScenicSpot();
};

const tableData = ref<ScenicSpot[]>([
  {
    id: "1",
    name: "张家界",
    pictureUrl: "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
    description: "1245ds",
  },
]);

const getAllScenicSpot = async () => {
  const res = await searchAllScenicSpotAPI(pageData.value.current, 5);

  if (res.data.code === "200") {
    console.log(res.data.data);
    tableData.value = res.data.data.data;

    pageData.value.total = res.data.data.total;

    srcList.value = res.data.data.data.map((item) => item.pictureUrl);
  } else {
    ElMessage.error(res.data.message);
  }
};

const deal = async () => {
  if (dialogTitle.value === "新建景点") {
    // 这边是新建
    const res = await createScenicSpotAPI(
      form.value.id,
      form.value.name,
      form.value.pictureUrl,
      form.value.description
    );

    if (res.data.code === "200") {
      ElMessage.success("新建成功");
      getAllScenicSpot();
    } else {
      ElMessage.error(res.data.message);
    }
  } else {
    // 编辑
    const res = await updateScenicSpotAPI(
      form.value.id,
      form.value.name,
      form.value.pictureUrl,
      form.value.description
    );

    if (res.data.code === "200") {
      ElMessage.success("修改成功");
      getAllScenicSpot();
    } else {
      ElMessage.error(res.data.message);
    }
  }

  dialogFormVisible.value = false;
  userFormRef.value.resetFields();
};

const rules = reactive({
  id: [{ required: true, message: "请输入id", trigger: "change" }],
  name: [{ required: true, message: "请输入名字", trigger: "change" }],
  pictureUrl: [{ required: true, message: "请上传图片", trigger: "change" }],
  description: [{ required: true, message: "请输入描述", trigger: "change" }],
});

const cancle = () => {
  dialogFormVisible.value = false;
};

onMounted(() => {
  getAllScenicSpot();

  if (userStore.getUser() === null) router.push("/login");
});
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

img {
  width: 120px;
  height: 80px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
